package com.hoo.controller.account;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hoo.common.constant.Constant;
import com.hoo.entity.account.SearchVisitorResult;
import com.hoo.entity.account.Visitor;
import com.hoo.form.account.SearchForm;
import com.hoo.form.account.VisitorForm;
import com.hoo.form.order.TicketOrderForm;
import com.hoo.service.account.VisitorService;
import com.hoo.util.DateUtils;
import com.hoo.util.PaginationSupport;

@Controller
public class VisitorController extends BaseController {

	@Autowired
	VisitorService visitorService;
	
	/**
	 * 根据年段进行统计
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/visitor/statistics/chart/age", method = RequestMethod.GET)
	public String chartAge(Model model) {
		return "statistics/age";
	}
	
	/**
	 * 根据年段进行统计
	 * @param request
	 * @param response
	 * @return
	 * @datestyleString resultString="[{name: 'Year 1800',data: [107, 31, 635, 203, 22,11,12,1000]}, {name: 'Year 1900',data: [133, 156, 947, 408, 60,13,13,1200]}, {name: 'Year 2012',data: [1052, 954, 250, 740, 38,14,13,1300]}]";
	 */
	@RequestMapping(value = "/visitor/statistics/chart/age",method = RequestMethod.POST)
	@ResponseBody
	public String doChartAge(HttpServletRequest request, HttpServletResponse response){
		writeContentToJSP(request,response,this.visitorService.getVisitorGroupMapYear());
		return null;
	}
	
	@RequestMapping(value = "/visitor/statistics/chart/eve_provice_visitor", method = RequestMethod.GET)
	public String chartEveProviceVisitor(Model model) {
		model.addAttribute("provices",this.visitorService.getAllProvices());
		return "statistics/proviceAndCity";
	}
	
	/**
	 *  对全国各省统计，图形报表信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/visitor/statistics/chart/eve_provice_visitor",method = RequestMethod.POST)
	@ResponseBody
	public String doChartEveProviceVisitor(HttpServletRequest request, HttpServletResponse response,SearchForm form){
		form.setEndTime(form.getEndTime()+" 23:59:59");
		writeContentToJSP(request,response,visitorService.getVisitorInEveProviceBetweenTime(form));
		return null;
	}
	
	/**
	 * 根据指定省份，统计下属市级游客，图形报表信息
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/chart/eve_city_visitor_inProvice" ,method=RequestMethod.POST)
	@ResponseBody
	public String doCharEveCityVisitor(HttpServletRequest request, HttpServletResponse response,SearchForm form){
		form.setEndTime(form.getEndTime()+" 23:59:59");
		writeContentToJSP(request,response,this.visitorService.getVisitorCityResults(form));
		return null;
	}

	/**
	 * 趋势分析跳转
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/visitor/statistics/chart/thirty_min_visitor", method = RequestMethod.GET)
	public String gotoTrend(Model model) {
		return "statistics/trend";
	}
	
	/**
	 * 查询最近三十分钟内游客报表信息 ，图形报表信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/chart/thirty_min_visitor",method=RequestMethod.POST)
	@ResponseBody
	public String doChartThirtyMin(HttpServletRequest request, HttpServletResponse response){
		writeContentToJSP(request,response,visitorService.statisticsVisitorInThirtyMin());
		return null;
	}
	
	/**
	 * 查询最近三十分钟内游客详细信息，datatable信息
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/search/thirty_min_visitor",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> doSearchThirtyMin(VisitorForm form ,HttpServletRequest request, HttpServletResponse response){
		PaginationSupport<Visitor> ps = visitorService.getVisitorInThirtyMin(form);
		return dataTableJson(ps.getTotalCount(), ps.getItems());
	}
	
	/**
	 * 查询今日或昨日游客报表信息，图形报表信息
	 * @param when
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/chart/{when}/day_visitor",method=RequestMethod.POST)
	@ResponseBody
	public String doChartInDay(@PathVariable String when,HttpServletRequest request, HttpServletResponse response,Model model,SearchForm form){
		if(when.equals("single")){
			writeContentToJSP(request,response,visitorService.getVisitorInDay(form));
		}else{
			writeContentToJSP(request,response,visitorService.getRecentVisitor(form));
		}
		
		/*if(when.equals("today")){
			map.put("minDate",DateUtils.getCurrentDate("yyyy-MM-dd 00:00:00"));
			map.put("maxDate", DateUtils.getCurrentDate("yyyy-MM-dd 23:59:59"));
		}else{
			map.put("minDate",DateUtils.getYesterdayDate("yyyy-MM-dd 00:00:00"));
			map.put("maxDate", DateUtils.getYesterdayDate("yyyy-MM-dd 23:59:59"));
		}
		writeContentToJSP(request,response,visitorService.getVisitorInDay(map));*/
		return null;
	}
	
	/**
	 * 查询一天当中每个小时的各种游客数量及所占比重，用于dataTable
	 * @param startTime
	 * @param endTime
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/search/visitor_info/{type}",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> searchVisitorInfoInDay(@PathVariable(value="type") String type,HttpServletRequest request, HttpServletResponse response,SearchForm form){
		PaginationSupport<SearchVisitorResult> ps =null;
		form.setEndTime(form.getEndTime()+" 23:59:59");
		if(type.equals("inday")){
			ps = visitorService.getVisitorInfoInDay(form);	
		}else {
			ps = visitorService.getVisitorInfoRecent(form);
		}
		return dataTableJson(ps.getTotalCount(), ps.getItems());
	}
	
	/**
	 * 统计指定时间段内的每天的各游客所占百分比情况
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/sta/eve_day_visitor",method=RequestMethod.POST)
	@ResponseBody
	public String doStatisticsEveDayVisitor(SearchForm form){
		//Map<String, Date> map=handleDate(startTime,endTime);
		SearchVisitorResult result=this.visitorService.statisticsPercent(form);
		Map<String, Object> map2=new HashMap<String, Object>();
		map2.put("totalCount", result.getStaCount());
		map2.put("scatteredCount",(result.getStaCount()-result.getStaGroupCount()));
		map2.put("meshCount",result.getStaInternetTradingCount());
		map2.put("totalCount",result.getStaCount());
		map2.put("groupCount",result.getStaGroupCount());
		//String jsonStr="{'totalCount':'"+result.getStaCount()+"','groupCount':'"+result.getSta_group_count()+"','groupPrecent':'"+result.getSta_group_count()/result.getStaCount()/100+"%','scatteredCount':'"+(result.getStaCount()-result.getSta_group_count())+"','scatteredPrecent':'"+(1-result.getSta_group_count()/result.getStaCount())/100+"%','meshCount':'"+result.getSta_internet_trading_count()+"','meshPrecent':'"+result.getSta_internet_trading_count()/result.getStaCount()/100+"%'}";
		if(result.getStaCount()==0){
			map2.put("groupPrecent","0.00%");
			map2.put("scatteredPrecent","0.00%");
			map2.put("meshPrecent","0.00%");
		}else {
			DecimalFormat decimalFormat=new DecimalFormat("0.00");
			map2.put("groupPrecent",decimalFormat.format(((float)result.getStaGroupCount()/result.getStaCount())*100)+"%");
			map2.put("scatteredPrecent",decimalFormat.format((1-(float)result.getStaGroupCount()/result.getStaCount())*100)+"%");
			map2.put("meshPrecent",decimalFormat.format(((float)result.getStaInternetTradingCount()/result.getStaCount())*100)+"%");
		}
		return JSONObject.fromObject(map2).toString();
	}
	
	/**
	 *统计指定时间段内每天游客信息，图形报表信息
	 * @param startTime
	 * @param endTime
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/chart/eve_day_visitor",method=RequestMethod.POST)
	@ResponseBody
	public String doChartEveDayVisitor(@RequestParam String startTime,@RequestParam String endTime,HttpServletRequest request, HttpServletResponse response){
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Map<String, Date> map=new HashMap<String, Date>();
		try {
			if(startTime.contains("/") && endTime.contains("/")){
				if(startTime.contains("?") && endTime.contains("?")){
					startTime = startTime.replaceAll("[?]", "");
					endTime = endTime.replaceAll("[?]", "");
				}else if(startTime.contains("&lrm;") && endTime.contains("&lrm;")){
					startTime = startTime.replaceAll("[&lrm;]", "");
					endTime = endTime.replaceAll("[&lrm;]", "");
				}
				map.put("startTime", DateUtils.getDate(startTime.replaceAll("/", "-"),Constant.DATE_FORMAT_SIMPLE));
				map.put("endTime", DateUtils.getDate(endTime.replaceAll("/", "-"),Constant.DATE_FORMAT_SIMPLE));
			}else{
				map.put("startTime", DateUtils.getDate(startTime.replaceAll("年", "-").replaceAll("月", "-").replaceAll("日", ""),Constant.DATE_FORMAT_SIMPLE));
				map.put("endTime", DateUtils.getDate(endTime.replaceAll("年", "-").replaceAll("月", "-").replaceAll("日", ""),Constant.DATE_FORMAT_SIMPLE));
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		//writeContentToJSP(request,response,visitorService.getRecentVisitor(map));
		return null;
	}
	
	/**
	 * 统计全国游客分布，在china地图上显示
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/chart/source_map",method=RequestMethod.GET)
	public String chartMap(Model model){
		model.addAttribute("provicesData", visitorService.mkData());
		return "statistics/sourceCountryMap";
	}
	
	@RequestMapping(value="/visitor/statistics/chart/eve_provice_visitor_pie",method=RequestMethod.GET)
	public String chartEveProvice(Model model){
		return "statistics/sourceProvicesPie";
	}
	
	/**
	 * 统计指定时间段内每个省份游客所占比重，用于饼状图
	 * @param startTime
	 * @param endTime
	 * @param request
	 * @param response
	 * @return
	 */
	/*@RequestMapping(value="/visitor/statistics/chart/eve_provice_visitor_pie",method=RequestMethod.POST)
	@ResponseBody
	public String doChartEveProvice(@RequestParam String startTime,@RequestParam String endTime,HttpServletRequest request,HttpServletResponse response){
		//writeContentToJSP(request,response,this.visitorService.getVisitorInEveProviceBetweenTime(handleDate(startTime,endTime)));
		return null;
	}
	*/
	
	@RequestMapping(value="/visitor/statistics/chart/eve_provice_visitor_pie",method=RequestMethod.POST)
	@ResponseBody
	public String doChartEveProvice(HttpServletRequest request,HttpServletResponse response,SearchForm form){
		writeContentToJSP(request,response,this.visitorService.getVisitorInEveProviceBetweenTime(form));
		return null;
	}
	
	
	/**
	 * 查询每个省份游客种类的数量及所占比重
	 * @param startTime
	 * @param endTime
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/search/eve_provice_visitor_inf",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> searchEveProviceVisitorInf(HttpServletRequest request, HttpServletResponse response,SearchForm form){
		PaginationSupport<SearchVisitorResult> ps =visitorService.statisticsEveProviceVisitorInf(form);
		return dataTableJson(ps.getTotalCount(), ps.getItems());
	}	
	
	/**
	 * 用于来源地分析统计页面之间的跳转
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/chart/source_stage",method=RequestMethod.GET)
	public String chartSourceStage(Model model){
		return "statistics/sourceStage";
	}
	
	/**
	 * 统计指定时间段内各年龄段游客信息
	 * @param startTime
	 * @param endTime
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/visitor/statistics/chart/stage_age",method = RequestMethod.POST)
	@ResponseBody
	public String doChartStageAge(HttpServletRequest request,HttpServletResponse response,SearchForm form){
        writeContentToJSP(request,response,this.visitorService.getVisitorGroupMapDay(form));
		return null;
	}
	
	/**
	 * 统计每个民族游客数量
	 * @param startTime
	 * @param endTime
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/visitor/statistics/chart/eve_nation_visitor",method=RequestMethod.POST)
	@ResponseBody
	public String doChartEveNationVisitor(HttpServletRequest request, HttpServletResponse response,SearchForm form){
		writeContentToJSP(request,response,this.visitorService.statisticsEveNationVisitor(form));
        return null;
	}

	@RequestMapping(value = "/ticket/order_ticket", method = RequestMethod.GET)
	public String orderTicket(Model model) {
		return "online/orderTicket";
	}
	
	/**
	 *前台页面使用ajax提交，后台返回预约号，根据预约号进行判断是否预订成功
	 * @param form
	 * @return
	 */
	@RequestMapping(value = "/ticket/order_ticket", method = RequestMethod.POST)
	@ResponseBody
	public String doOrderTicket(TicketOrderForm form) {
		return this.visitorService.insertVisitorHanderOnline(form);
	}
	
	private void writeContentToJSP(HttpServletRequest request,HttpServletResponse response,Object object){
		JSONArray jsonArray=JSONArray.fromObject(object);
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");  
        PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}  
        out.print(jsonArray.toString());
        out.flush();
        out.close();
	}
	private Map<String, Date> handleDate(String startTime,String endTime,HttpServletRequest request){
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		Map<String, Date> map=new HashMap<String, Date>();
		try {
			if(startTime.contains("/") && endTime.contains("/")){
				if(startTime.contains("?")&& endTime.contains("?")){
					startTime = startTime.replaceAll("[?]", "");
					endTime = endTime.replaceAll("[?]", "");
				}else if(startTime.contains("&lrm;") && endTime.contains("&lrm;")){
					startTime = startTime.replaceAll("[&lrm;]", "");
					endTime = endTime.replaceAll("[&lrm;]", "");
				}
				map.put("startTime", DateUtils.getDate(DateUtils.beginOfDate(startTime.replaceAll("/", "-")),"yyyy-MM-dd 00:00:00"));
				map.put("endTime", DateUtils.getDate(DateUtils.endOfDate(endTime.replaceAll("/", "-")),Constant.DATE_FORMAT_LONG_ONE));
			}else{
				map.put("startTime", DateUtils.getDate(DateUtils.beginOfDate(startTime.replaceAll("年", "-")).replaceAll("月", "-").replaceAll("日", ""),"yyyy-MM-dd 00:00:00"));
				map.put("endTime", DateUtils.getDate(DateUtils.beginOfDate(endTime.replaceAll("年", "-")).replaceAll("月", "-").replaceAll("日", ""),Constant.DATE_FORMAT_LONG_ONE));
			}
		}catch (ParseException e){
			e.printStackTrace();
		}
		return map;
	}
	private Map<String, Date> handleDate(String startTime,String endTime){
		Map<String, Date> map=new HashMap<String, Date>();
		try {
			if(startTime.contains("/") && endTime.contains("/")){
				if(startTime.contains("?")&& endTime.contains("?")){
					startTime = startTime.replaceAll("[?]", "");
					endTime = endTime.replaceAll("[?]", "");
				}else if(startTime.contains("&lrm;") && endTime.contains("&lrm;")){
					startTime = startTime.replaceAll("[&lrm;]", "");
					endTime = endTime.replaceAll("[&lrm;]", "");
				}
				map.put("startTime", DateUtils.getDate(DateUtils.beginOfDate(startTime.replaceAll("/", "-")),"yyyy-MM-dd 00:00:00"));
				map.put("endTime", DateUtils.getDate(DateUtils.endOfDate(endTime.replaceAll("/", "-")),Constant.DATE_FORMAT_LONG_ONE));
			}else{
				map.put("startTime", DateUtils.getDate(DateUtils.beginOfDate(startTime.replaceAll("年", "-")).replaceAll("月", "-").replaceAll("日", ""),"yyyy-MM-dd 00:00:00"));
				map.put("endTime", DateUtils.getDate(DateUtils.beginOfDate(endTime.replaceAll("年", "-")).replaceAll("月", "-").replaceAll("日", ""),Constant.DATE_FORMAT_LONG_ONE));
			}
		}catch (ParseException e){
			e.printStackTrace();
		}
		return map;
	}
}
